package com.ruoyi.socket.manager;

import com.ruoyi.socket.config.HuobiWebSocketConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 火币连接管理器
 * 管理连接状态，实现智能重连和地址切换
 */
@Component
@Slf4j
public class HuobiConnectionManager {
    
    @Resource
    private HuobiWebSocketConfig huobiWebSocketConfig;
    
    /**
     * 连接失败计数器
     */
    private final AtomicInteger failureCount = new AtomicInteger(0);
    
    /**
     * 连接状态映射
     */
    private final ConcurrentHashMap<String, Boolean> connectionStatus = new ConcurrentHashMap<>();
    
    /**
     * 最后连接时间
     */
    private volatile long lastConnectTime = 0;
    
    /**
     * 获取当前WebSocket URL
     */
    public String getCurrentWebSocketUrl() {
        return huobiWebSocketConfig.buildWebSocketUrl();
    }
    
    /**
     * 处理连接失败
     * @param reason 失败原因
     * @return 是否需要切换地址
     */
    public boolean handleConnectionFailure(String reason) {
        int currentFailures = failureCount.incrementAndGet();
        String currentUrl = huobiWebSocketConfig.getCurrentUrl();
        
        log.warn("火币WebSocket连接失败 [{}]: {}, 当前失败次数: {}", 
                currentUrl, reason, currentFailures);
        
        // 记录连接状态
        connectionStatus.put(currentUrl, false);
        
        // 如果连接失败次数达到阈值，切换地址
        if (currentFailures >= huobiWebSocketConfig.getMaxRetries()) {
            return switchToNextUrl();
        }
        
        return false;
    }
    
    /**
     * 切换到下一个地址
     */
    private boolean switchToNextUrl() {
        String oldUrl = huobiWebSocketConfig.getCurrentUrl();
        String newUrl = huobiWebSocketConfig.switchToNextUrl();
        
        // 重置失败计数
        failureCount.set(0);
        
        log.info("火币WebSocket切换地址: {} -> {}", oldUrl, newUrl);
        return true;
    }
    
    /**
     * 处理连接成功
     */
    public void handleConnectionSuccess() {
        String currentUrl = huobiWebSocketConfig.getCurrentUrl();
        
        // 重置失败计数
        failureCount.set(0);
        
        // 记录连接状态
        connectionStatus.put(currentUrl, true);
        lastConnectTime = System.currentTimeMillis();
        
        log.info("火币WebSocket连接成功: {}", currentUrl);
    }
    
    /**
     * 获取连接状态
     */
    public boolean isConnected() {
        String currentUrl = huobiWebSocketConfig.getCurrentUrl();
        return connectionStatus.getOrDefault(currentUrl, false);
    }
    
    /**
     * 获取失败次数
     */
    public int getFailureCount() {
        return failureCount.get();
    }
    
    /**
     * 获取最后连接时间
     */
    public long getLastConnectTime() {
        return lastConnectTime;
    }
    
    /**
     * 重置连接状态
     */
    public void resetConnectionStatus() {
        failureCount.set(0);
        connectionStatus.clear();
        huobiWebSocketConfig.resetToFirstUrl();
        log.info("火币WebSocket连接状态已重置");
    }
    
    /**
     * 获取所有配置的URL
     */
    public java.util.List<String> getAllUrls() {
        return huobiWebSocketConfig.getUrls();
    }
    
    /**
     * 获取当前URL索引
     */
    public int getCurrentUrlIndex() {
        return huobiWebSocketConfig.getCurrentUrlIndex();
    }
    
    /**
     * 获取连接状态信息
     */
    public String getConnectionStatusInfo() {
        return String.format("当前地址: %s (索引: %d/%d), 失败次数: %d, 连接状态: %s, 最后连接时间: %d",
                huobiWebSocketConfig.getCurrentUrl(),
                huobiWebSocketConfig.getCurrentUrlIndex(),
                huobiWebSocketConfig.getUrlCount() - 1,
                failureCount.get(),
                isConnected() ? "已连接" : "未连接",
                lastConnectTime);
    }
} 